import logging
import os
from WXBizMsgCrypt import WXBizMsgCrypt
import xml.etree.cElementTree as ET
from flask import Flask, request, make_response, render_template

# 创建 Flask 应用实例，并指定模板文件夹的绝对路径
app = Flask(__name__,)
# 设置日志等级为DEBUG，并指定日志输出文件
logging.basicConfig(filename='logfile.log', level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s')

sToken = "OsJasOo95FqjLlRkX8MapuAlHwRPr"
sEncodingAESKey = "RRkdYXys5S8agW1FXabdu5RIAdC2d3OpT3TFSKmCkTJ"
sCorpID = "wwecebefe9c58927cc"


@app.route('/wxpush', methods=['GET'])
def wx_auth():
    wxcpt = WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID)
    msg_signature = request.args.get('msg_signature', "")
    timestamp = request.args.get('timestamp', "")
    nonce = request.args.get('nonce', "")
    echostr = request.args.get('echostr', "")
    logging.debug(f"Received parameters: {msg_signature}, {timestamp}, {nonce}, {echostr}")

    ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
    if ret != 0:
        logging.error(f"ERR: VerifyURL ret: {ret}")
        return "Error", 500

    # 验证URL成功，将sEchoStr返回给企业号
    response = make_response(sEchoStr, 200)
    response.content_type = "text/plain"
    return response


@app.route('/wx', methods=['GET'])
def index():
    return render_template('index.html')


if __name__ == "__main__":
    app.run(port=8001)